package com.fanqwz.kotlinmvvm.data.repository

import com.fanqwz.kotlinmvvm.data.persist.db.UserDatabase
import com.fanqwz.kotlinmvvm.data.persist.po.UserPO
import com.fanqwz.kotlinmvvm.data.persist.po.UserPOfromEntity
import com.fanqwz.kotlinmvvm.data.web.entity.LoginRequestBody
import com.fanqwz.kotlinmvvm.data.web.entity.toUser
import com.fanqwz.kotlinmvvm.data.web.iface.Backend
import com.fanqwz.kotlinmvvm.data.web.RequestTemplate
import com.fanqwz.kotlinmvvm.data.web.iface.LoginHeader
import com.fanqwz.kotlinmvvm.domain.`object`.Session
import com.fanqwz.kotlinmvvm.domain.`object`.User
import com.fanqwz.kotlinmvvm.domain.repo.UserRepository
import io.reactivex.Flowable
import org.intellij.lang.annotations.Flow
import javax.inject.Inject

/**
 * Created by fanqwz on 2018/3/1.
 */


/** repository中使用同步调用，在usecase中实现异步处理，尽量简化data层逻辑*/
class UserDataRepository @Inject constructor() : BaseObServableRepository(), UserRepository {
    @Inject
    lateinit var backend: Backend
    @Inject
    lateinit var database: UserDatabase

    override fun logon(name: String, passwd: String): Flowable<User> {
        return Flowable.just(User(0, name, passwd))
    }

    override fun session(user: User): Flowable<Session> {
        return Flowable.just(Session("sessionabc"))
    }

    override fun login(code: String, passwd: String): Flowable<User> {
        return Flowable.unsafeCreate<User> { e ->
            val user = backend.login(RequestTemplate(LoginRequestBody(code, passwd), LoginHeader)).execute().body()?.body
            if (user != null) {
                if (database.userDao().getUser(code.toUpperCase(), passwd) == null)
                    database.userDao().insertUSer(UserPOfromEntity(user))
                e.onNext(user.toUser())
                e.onComplete()
            } else {
                e.onError(Exception("use is null"))
            }
        }
    }
}